package com.example.upload.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;

@Service
public class PythonExecutor {

    @Value("${python.path}")
    private String pythonPath;

    public String executeScript(String... params) {

        // 获取资源文件的绝对路径
        File scriptFile = null;
        try {
            scriptFile = new File(PythonExecutor.class.getResource("/script/爬虫_抖音_Selenium_传参.py").toURI());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }



        ProcessBuilder processBuilder = new ProcessBuilder();

        // 构建命令
        processBuilder.command(pythonPath, scriptFile.getAbsolutePath());

        // 添加参数
        for (String param : params) {
            processBuilder.command().add(param);
        }

        StringBuilder output = new StringBuilder();
        StringBuilder errorOutput = new StringBuilder(); // 用于收集错误输出
        try {
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); // 读取错误流
            String line;

            // 读取输出
            while ((line = reader.readLine()) != null) {
                output.append(line).append(System.lineSeparator());
            }

            // 读取错误输出
            while ((line = errorReader.readLine()) != null) {
                errorOutput.append(line).append(System.lineSeparator());
            }


            // 等待进程结束
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("Python script failed with exit code: " + exitCode + "\nError Output:\n" + errorOutput.toString());
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        return output.toString().trim();
    }

    public static void main(String[] args) {
        PythonExecutor executor = new PythonExecutor(); // 或者 "python3"

        String output = executor.executeScript("6.64 Chb:/ V@Y.ZZ 11/16 罗非鱼中毒团灭，生态系统迎来新生命# 室内农场 # 生态循环 # 鱼菜共生 # 沙雕日常 https://v.douyin.com/iSwe6oek/");

        System.out.println("Script Output:\n" + output);
    }
}
